package com.yanqu.road.server.manger.activity;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.game.ActivityPageantInfo;
import com.yanqu.road.entity.activity.game.config.*;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.logic.bussiness.activity.PageantBussiness;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.game2048.PageantModule;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class GamePageantMgr extends TempMgr {

    /**
     * 活动参数
     * params1: 资源目录
     * params2: 重置方式
     * params3: 条件文本，比如排行中的涨幅文本、总分数  0;沉鱼落雁，闭月羞花之貌|2000;沉鱼落雁，闭月羞花，倾国倾城|20000;沉鱼落雁，闭月羞花，倾国倾城，国色天香，巴拉巴拉。
     * params4:   上限|恢复周期秒|恢复点 30|200|5
     * params5:   普通场和高级场配置：60;30;10|0;0;100
     * params6:    选美币道具ID|重排道具ID|消除道具ID|体力恢复道具ID  101906|110121|110120|110119
     */

    /**
     * 开服加载数据   用户也有这个数据(需要同步更新)
     */
    private static Logger logger = LogManager.getLogger(GamePageantMgr.class.getName());

    private static ActivityInfo activityInfo;

    /**
     * 结算文本描述
     */
    private static List<DescConfig> descConfig = new ArrayList<>();

    /**
     * 道具id列表
     */
    private static GoodsConfig goodsConfig = new GoodsConfig();

    /**
     * 道具使用次数限制  重排 消除
     */
    private static int goodsTimesChongPai = 9999;
    private static int goodsTimesXiaochu = 9999;

    /**
     *  基础权重  100
     */
    private static int baseWeight = 100;

    /**
     * 高级权限开关 默认关  0关  1开
     */
    private static int weightOnOff = 0;

    /**
     * 16倍场解锁VIP等级
     */
    private static int fastUnlockVipLevel = Integer.MAX_VALUE;

    public static int getBaseWeight() {
        return baseWeight;
    }

    public static int getWeightOnOff() {
        return weightOnOff;
    }

    public static int getGoodsTimesChongPai() {
        return goodsTimesChongPai;
    }

    public static int getGoodsTimesXiaochu() {
        return goodsTimesXiaochu;
    }

    /**
     * 活动概率
     */
    private static ProbabilityConfig normalProbabilityConfig = new ProbabilityConfig();//普通场
    private static ProbabilityConfig highProbabilityConfig = new ProbabilityConfig();//高级场
    private static String fastProbabilityConfig = ""; // 急速场（级别1,级别2;权重1,权重2）

    /**
     * 体力配置
     */
    private static StrengthConfig strengthConfig = new StrengthConfig();

    public static List<DescConfig> getDescConfig() {
        return descConfig;
    }

    public static void setDescConfig(List<DescConfig> descConfig) {
        GamePageantMgr.descConfig = descConfig;
    }

    public static GoodsConfig getGoodsConfig() {
        return goodsConfig;
    }

    public static void setGoodsConfig(GoodsConfig goodsConfig) {
        GamePageantMgr.goodsConfig = goodsConfig;
    }

    public static ProbabilityConfig getNormalProbabilityConfig() {
        return normalProbabilityConfig;
    }

    public static void setNormalProbabilityConfig(ProbabilityConfig normalProbabilityConfig) {
        GamePageantMgr.normalProbabilityConfig = normalProbabilityConfig;
    }

    public static ProbabilityConfig getHighProbabilityConfig() {
        return highProbabilityConfig;
    }

    public static void setHighProbabilityConfig(ProbabilityConfig highProbabilityConfig) {
        GamePageantMgr.highProbabilityConfig = highProbabilityConfig;
    }

    public static String getFastProbabilityConfig() {
        return fastProbabilityConfig;
    }

    public static int getFastUnlockVipLevel() {
        return fastUnlockVipLevel;
    }

    public static StrengthConfig getStrengthConfig() {
        return strengthConfig;
    }

    public static void setStrengthConfig(StrengthConfig strengthConfig) {
        GamePageantMgr.strengthConfig = strengthConfig;
    }

    public static List<ActivityPageantInfo> getBeautyConfigList() {
        return beautyConfigList;
    }

    public static void setBeautyConfigList(List<ActivityPageantInfo> beautyConfigList) {
        GamePageantMgr.beautyConfigList = beautyConfigList;
    }

    public static void reloadActivityInfo() {
        //选美大会活动加载
        loadActivity();
    }


    /**
     *
     */
    public static void loadGoodsConfig(ActivityInfo activity) {
        if (null != activity) {

            String params3 = activity.getParam3();//结算文本配置
            String[] desConfigs = params3.split("\\|");
            for (String desConfig : desConfigs) {
                String[] config = desConfig.split(";");
                if (config.length == 2) {
                    DescConfig con = new DescConfig();
                    con.setScore(Integer.valueOf(config[0]));
                    con.setDescription(config[1]);
                    descConfig.add(con);
                }
            }

            String params4 = activity.getParam4();//上限|恢复周期秒|恢复点
            String[] strength = params4.split("\\|");
            StrengthConfig sconf = new StrengthConfig();
            if (strength.length == 3) {
                sconf.setMaxStrength(Integer.valueOf(strength[0]));
                sconf.setSecends(Integer.valueOf(strength[1]));
//                sconf.setSecends(60);
                sconf.setAddStrength(Integer.valueOf(strength[2]));
                strengthConfig = sconf;
            }

            String params5 = activity.getParam5();// 普通场和高级场配置：60;30;10|0;0;100
            String[] prob = params5.split("\\|");
            String[] p1 = prob[0].split(";");
            ProbabilityConfig normal = new ProbabilityConfig();
            if (p1.length == 3) {
                normal.setOneLevel(Integer.valueOf(p1[0]));
                normal.setTwoLevel(Integer.valueOf(p1[1]));
                normal.setThreeLevel(Integer.valueOf(p1[2]));
                normalProbabilityConfig = normal;
            }

            String[] p2 = prob[1].split(";");
            if (p2.length == 3) {
                ProbabilityConfig high = new ProbabilityConfig();
                high.setOneLevel(Integer.valueOf(p2[0]));
                high.setTwoLevel(Integer.valueOf(p2[1]));
                high.setThreeLevel(Integer.valueOf(p2[2]));
                highProbabilityConfig = high;
            }

            //新增高级算法概率 默认权重100 默认关
            if(prob.length>2&&!StringUtils.isNullOrEmpty(prob[2])){
                baseWeight = Integer.valueOf(prob[2]);
            }

            //0关  1开
            if(prob.length>3&&!StringUtils.isNullOrEmpty(prob[3])){
                weightOnOff = Integer.valueOf(prob[3]);
            }

            if (prob.length >= 6) {
                fastProbabilityConfig = prob[4];
                fastUnlockVipLevel = Integer.valueOf(prob[5]);
            } else {
                fastProbabilityConfig = "";
                fastUnlockVipLevel = Integer.MAX_VALUE;
            }

            //选美币道具ID|重排道具ID|消除道具ID|体力恢复道具ID  101906|110121|110120|110119
            String params6 = activity.getParam6();
            String[] goods = params6.split("\\|");
            GoodsConfig gConfig = new GoodsConfig();
            if (goods.length == 4) {
                gConfig.setPageantMoneyId(Integer.valueOf(goods[0]));
                gConfig.setPageantRearrange(Integer.valueOf(goods[1]));
                gConfig.setPageantMurder(Integer.valueOf(goods[2]));
                gConfig.setRestoreStrength(Integer.valueOf(goods[3]));
                goodsConfig = gConfig;
            }

            GoodsInfo chongpai = GoodsMgr.getGoodsById(goodsConfig.getPageantRearrange());
            if (null != chongpai && chongpai.getParamStr() != null) {
                BigInteger chongpaiSystem = chongpai.getParamList().get(1);
                goodsTimesChongPai = chongpaiSystem.intValue();
            }

            GoodsInfo xiaochu = GoodsMgr.getGoodsById(goodsConfig.getPageantMurder());
            if (null != xiaochu && xiaochu.getParamStr() != null) {
                BigInteger xiaochuSystem = xiaochu.getParamList().get(1);
                goodsTimesXiaochu = xiaochuSystem.intValue();
            }
        }
    }


    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }


    /**
     * 选美大会活动加载
     */
    public static void loadActivity() {
        List<ActivityInfo> activityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.PageantActivity.getValue());
        ActivityInfo inTimeActivity = null;
        for (ActivityInfo ac : activityInfoList) {
            if (ac.getType() == eActivityType.PageantActivity.getValue()) {
                inTimeActivity = ac;
                break;
            }
        }
        if (inTimeActivity != null) {
            //选美大会分数机制 加载美女数据
            scoreRule(inTimeActivity.getActivityId());
            //宝箱概率
            setBoxConfig();
            //加载活动配置
            loadGoodsConfig(inTimeActivity);
        }

        activityInfo = inTimeActivity;

        List<GamePlayer> playerList = GamePlayerMgr.getCopyPlayerList();
        if (playerList != null && playerList.size() > 0) {
            playerList.forEach(action -> {
                action.getModule(PageantModule.class).syncActivity();
            });
        }
    }

    public static ActivityInfo getActivityInfo() {
        return activityInfo;
    }

    public static void setActivityInfo(ActivityInfo activityInfo) {
        GamePageantMgr.activityInfo = activityInfo;
    }


    /**
     * 获取选美大会分数配置
     */
    private static List<ActivityPageantInfo> beautyConfigList = new ArrayList<>();

    /**
     * 等级  美女配置
     */
    private static Map<Integer, ActivityPageantInfo> configBeautyMap = new ConcurrentHashMap<>();

    /**
     * 等级  宝盒配置
     */
    private static Map<Integer, List<BoxConfig>> configBoxMap = new ConcurrentHashMap<>();

    public static Map<Integer, List<BoxConfig>> getConfigBoxMap() {
        return configBoxMap;
    }

    public static void setConfigBoxMap(Map<Integer, List<BoxConfig>> configBoxMap) {
        GamePageantMgr.configBoxMap = configBoxMap;
    }

    public static Map<Integer, ActivityPageantInfo> getConfigBeautyMap() {
        return configBeautyMap;
    }

    public static void setConfigBeautyMap(Map<Integer, ActivityPageantInfo> configBeautyMap) {
        GamePageantMgr.configBeautyMap = configBeautyMap;
    }

    /**
     * 加载活动美女分数值
     */
    public static void scoreRule(int activityId) {
        beautyConfigList = PageantBussiness.getPageantConfig(activityId);
        Map<Integer, ActivityPageantInfo> map = new ConcurrentHashMap<>();
        for (ActivityPageantInfo config : beautyConfigList) {
            map.put(config.getLevel(), config);
        }
        configBeautyMap = map;
    }

    public static void setBoxConfig() {
        Map<Integer, List<BoxConfig>> map = new ConcurrentHashMap<>();
        for (ActivityPageantInfo data : configBeautyMap.values()) {
            String randomBoxStr = data.getRandomBox();
            //20;110069=1|5;110070=1
            if (!StringUtils.isNullOrEmpty(randomBoxStr) && !randomBoxStr.equals("0")) {
                List<String> randomBoxs = StringUtils.stringToStringList(randomBoxStr, "\\|");
                List<BoxConfig> boxConfigs = new ArrayList<>();
                for (String randomBox : randomBoxs) {
                    //20;110069=1
                    BoxConfig boxConfig = new BoxConfig();
                    if (!randomBox.equals("0")) {
                        String[] properties = randomBox.split(";");
                        boxConfig.setProbability(Integer.valueOf(properties[0]));
                        String[] goosIdAndNum = properties[1].split("=");
                        boxConfig.setGoodsId(Integer.valueOf(goosIdAndNum[0]));
                        boxConfig.setNum(Integer.valueOf(goosIdAndNum[1]));
                        boxConfigs.add(boxConfig);
                    }
                }
                map.put(data.getLevel(), boxConfigs);
            }
        }
        configBoxMap = map;
    }

    /**
     * 计算生成美女时获得的积分数
     */
    public static int calcCreateScore(int level) {
        int score = 0;
        int num = 1;
        for (int i = level; i > 0; i--) {
            ActivityPageantInfo pageantInfo = configBeautyMap.get(i);
            if (pageantInfo == null) return 0; // 配置有问题就都不给
            int scoreMerge = pageantInfo.getSorceMerge();
            score = score + scoreMerge * num;
            num = num * 2;
        }
        return score;
    }

    /**
     * 计算生成美女时获得的选美币
     */
    public static int calcCreateMoney(int level) {
        int money = 0;
        int num = 1;
        for (int i = level; i > 0; i--) {
            ActivityPageantInfo pageantInfo = configBeautyMap.get(i);
            if (pageantInfo == null) return 0; // 配置有问题就都不给
            int moneyMerge = pageantInfo.getMoneyMerge();
            money = money + moneyMerge * num;
            num = num * 2;
        }
        return money;
    }

    /**
     * 后台指令
     */
    public static void changePaint(Long userId, String paint) {
//        UserPageantData data = pageantDataMap.get(userId);
//        data.setPaint(paint);
//        pageantDataMap.put(userId,data);
//        UserPageantBussiness.insertGameInitData(data);
    }

}

